package onlinebanking.server.objects;

import onlinebanking.exceptions.UserNotLoggedInException;
import onlinebanking.network.Message;

public class Session extends QueryObject{
	protected int sessionID;
	/**
	 * Details of the currently logged in user
	 */
	protected PersonalAccount userAccount = null;
	/**
	 * Bank account where the current transaction requests are made
	 */
	protected BankAccount activeBankAccount = null;
	
	
	/**
	 * Sets the current user
	 * @param userAcccount Personal account of the current user
	 */
	public void setUserAccount(PersonalAccount userAcccount) {
		this.userAccount = userAcccount;
	}
	
	/**
	 * Sets the current active bank account
	 * @param activeBankAccount Bank account to be set as active
	 */
	public void setActiveBankAccount(BankAccount activeBankAccount){
		this.activeBankAccount = activeBankAccount;
	}
	
	/**
	 * Gets the details of the currently logged in user. 
	 * Returns a the first instance of an owned bank account as a default value.
	 * @return PersonalAccount of the user
	 * @throws UserNotLoggedInException	thrown when the client is not logged in
	 */
	public PersonalAccount getUserAccount() throws UserNotLoggedInException {
		if (this.userAccount != null)
			return this.userAccount;

		throw new UserNotLoggedInException("User Not Logged in: getUserAccount");
	}

	/**
	 * Gets the current active bank account of the user
	 * @return the active bank account
	 * @throws UserNotLoggedInException thown when client is not logged in
	 */
	public BankAccount getActiveBankAccount() throws UserNotLoggedInException {
		if (activeBankAccount != null) {
			return this.activeBankAccount;
		} else {
			if (this.userAccount == null) {
				throw new UserNotLoggedInException(
						"User Not Logged in: getActiveBankAccounts");
			}
		
			Message bankaccountmsg = BankAccount.getBankAccounts(userAccount.personalaccountid);
			
			//get number of bank accounts associated with the personal account
			int noOfAccounts = bankaccountmsg.getInt("count");
			
			if(noOfAccounts >= 1){
				System.out.println("Loading default bank account");
				//if only 1 bank account exist
				String accountno = bankaccountmsg.getString("#1");
				this.activeBankAccount = new BankAccount(0,Integer.parseInt(accountno));
			}

			return activeBankAccount;
		}

	}

}

